package cn.golxen;

import cn.golxen.commons.exception.GatewayException;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class LoginGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request对象
        HttpRequest request = exchange.getRequest();
        // 获取请求地址--带http的全部路径
        URI uri = request.getURI();
        // 获取请求路径--http://ip:port 后面的请求路径/student/account/login
        String path = uri.getPath();
        // 获取请求头
        HttpHeaders headers = request.getHeaders();
        try {
            // 从请求头中获取token 如果token不存在，则会赋值空
            List<String> list1 = headers.get("token");
        }catch (Exception e){
            throw new GatewayException();
        }
        List<String> list = headers.get("token");
        // 如果请求地址是登录请求的地址，则直接放行
        if(StringUtils.equals(path,"/user/login") || StringUtils.equals(path,"/user/adduser") ){
            return chain.filter(exchange);
        }
        // 如果不是登录请求的地址，就判断存放token的集合是否非空或长度大于0，如果是则说明携带了token，放行
        else if(!CollectionUtils.isEmpty(list) && list.size() > 0&& list.get(0) !=null){
            // 这里可以进一步判断token携带的值是否和该用户登录时生成的值相同
            return chain.filter(exchange);
        }else{
            // 如果不是登录请求，并且未携带token，则直接返回错误信息，提示登录
            ServerHttpResponse response = exchange.getResponse();
            DataBuffer buffer = response.bufferFactory().wrap(("{\n"
                    + "  \"code\": \"888\","
                    + "  \"message\": \"请登录\","
                    + "  \"data\": \"Server throttling\","
                    + "  \"success\": false"
                    + "}").getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}